#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
using namespace std;
int tickets=10000;
// pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
class TData
{
public:
    TData(const string &name,pthread_mutex_t *mutex):_name(name),_pmutex(mutex)
    {}
    ~TData()
    {}
public:
    string _name;
    pthread_mutex_t*_pmutex;
};
void* threadRoutine(void*args)
{
    TData*td=static_cast<TData*>(args);
    while(true)
    {
        pthread_mutex_lock(td->_pmutex);
        if(tickets>0)
        {
            usleep(2000);
            cout<<td->_name<<"get a ticket:"<<tickets--<<endl;
            pthread_mutex_unlock(td->_pmutex);

        }
        else
        {
            pthread_mutex_unlock(td->_pmutex);
            break;
        }
        // usleep(100);
    }
    return nullptr;
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    pthread_t tids[4];
    int n=sizeof(tids)/sizeof(tids[0]);
    for(int i=0;i<n;i++)
    {
        char*name;
        snprintf(name,64,"thread-%d",i+1);
        TData*td=new TData(name,&mutex);
        pthread_create(tids+i,nullptr,threadRoutine,td);
    }
    for(int i=0;i<n;i++)
    {
        pthread_join(tids[i],nullptr);
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}